package com.ubs.training.server.dao.impl.jdbc;

import com.ubs.training.server.dao.EmployeeDao;
import com.ubs.training.server.dao.model.Employee;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/21/12
 * Time: 3:50 AM
 * To change this template use File | Settings | File Templates.
 */
public class NamedParamEmployeeDaoImpl implements EmployeeDao {

    private DataSource ds;
    private NamedParameterJdbcOperations ops;

    public DataSource getDs() {
        return ds;
    }

    public void setDs(DataSource ds) {
        this.ds = ds;
        ops = new NamedParameterJdbcTemplate(ds);
    }


    @Override
    public List<Employee> getAll() {

        return ops.query("SELECT * FROM EMPLOYEE", Collections.EMPTY_MAP,
                new BeanPropertyRowMapper<Employee>(Employee.class)
        );

    }

    @Override
    public Employee getById(int id) {

        return ops.queryForObject("SELECT * FROM EMPLOYEE " +
                "WHERE ID=:EmployeeID", Collections.singletonMap("EmployeeID", id),
                new BeanPropertyRowMapper<Employee>(Employee.class)
        );

    }

    @Override
    public void add(Employee e) {

        int id = ops.queryForInt("SELECT NEXT VALUE FOR cmstr_seq from dual", Collections.EMPTY_MAP);
        e.setId(id);

        ops.update("INSERT INTO EMPLOYEE " +
                "VALUES (:id, :fname, :lname, :department, :pos)",
                new BeanPropertySqlParameterSource(e)
        );

    }

    @Override
    public void update(Employee e) {

        ops.update("UPDATE EMPLOYEE " +
                "SET fname=:fname, lname=:lname, " +
                "department=:department, pos=:pos " +
                "WHERE id=:id", new BeanPropertySqlParameterSource(e)
        );

    }

    @Override
    public void delete(int id) {
        ops.update("DELETE FROM employee WHERE id =:id",Collections.singletonMap("id", id));
    }
}
